<template>
    <el-dialog v-model="show" title="付款" width="35%" align-center @close="handleClose">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
            status-icon>

            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="所属公司：">
                        {{ props.initList.companyName }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="收款方名称：">
                        {{ props.initList.collectName }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="抵扣金额：">
                        ￥{{ props.initList.damageAmount }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="申请付款金额：">
                        ￥{{ props.initList.reconciliationAmount }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="已付款金额：">
                        ￥{{ props.initList.paidAlready }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="未付款金额：">
                        ￥{{ Number(props.initList.reconciliationAmount) - Number(props.initList.paidAlready) }}
                    </el-form-item>
                </el-col>
            </el-row>

            <el-divider />

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="付款账号:" prop="paymentAccountId">
                        <el-select style="width: 100%;" @change="monitorCheng" v-model="ruleForm.paymentAccountId"
                            placeholder="请选择付款账号">
                            <el-option v-for="item in props.allPaymentCardList" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="付款日期:" prop="paymentDate">
                        <el-date-picker @change="monitorCheng" v-model="ruleForm.paymentDate" format="YYYY/MM/DD"
                            value-format="YYYY-MM-DD" type="date" placeholder="请选择日期" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="付款金额:" prop="paymentAmount">
                        <el-input @change="monitorCheng" v-model.number="ruleForm.paymentAmount"
                            placeholder="请输入付款金额" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="付款人/单位:" prop="payer">
                        <el-input @change="monitorCheng" v-model="ruleForm.payer" placeholder="请输入付款人/单位" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="付款信息:" prop="paymentInfo">
                        <el-input v-model="ruleForm.paymentInfo" placeholder="付款信息" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="凭证上传:" prop="fileUrl">
                        <el-upload ref="designSketchRef" :show-file-list="false" drag :action="uploadImgUrl"
                            :headers="headers" multiple :auto-upload="true" :on-success="handleDesignSketchSuccess"
                            :before-upload="beforedeSignSketchUpload">
                            <img style="height: 100px;" v-if="ruleForm.fileUrl" :src="ruleForm.fileUrl" />
                            <template v-else>
                                <div style="padding-top: 10px;">
                                    <uploadStyle type="1" icon="PictureFilled" />
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-col>


                <template v-if="props.initList.collectType == 2">
                    <el-col :span="24">
                        <div style="color: #69AFF0;">可抵扣信息</div>
                    </el-col>

                    <el-col :span="24">
                        <div style="max-height: 200px; overflow-x: auto;">
                            <el-table :data="tableData" style="width: 100%">
                                <el-table-column prop="date" label="日期" />
                                <el-table-column prop="name" label="规格名称" />
                                <el-table-column prop="address" label="不合格数量" />
                                <el-table-column prop="address" label="来源" />
                                <el-table-column prop="address" label="可抵扣金额" />
                                <el-table-column label="操作" width="220px">
                                    <template #default="scope">
                                        <div style="display: flex;">
                                            <el-input v-model="ruleForm.paymentAccountId" placeholder="请输入抵扣数量" />
                                            <div>抵扣金额：￥10.00</div>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-col>
                </template>
                <template v-else>
                    <el-col :span="24">
                        <div style="color: red;">此条付款信息中，不存在可抵扣的货损产品</div>
                    </el-col>
                </template>
            </el-row>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="handleSubmit(ruleFormRef)">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import uploadStyle from '@/views/productManagement/designerTakesOrders/components/uploadStyle.vue';
import { addAccountsPayableApi } from '@/api/sj/financialManagement/accountsPayable'


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList', 'type', 'allPaymentCardList']);
const emits = defineEmits(['submit', 'close']);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);

const show = ref(false);
const dialogVisible = ref();


watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {
    }
}, { deep: true });

interface RuleForm {
    paymentAccountId: null | number
    paymentDate: string
    paymentAmount: null | number
    payer: string
    paymentInfo: string
    fileUrl: string
};
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    paymentAccountId: null,
    paymentAmount: null,
    paymentDate: '',
    payer: '',
    paymentInfo: '',
    fileUrl: '',
})

const tableData = [
    {
        date: '2016-05-03',
        name: 'Tom',
        address: 'No. 189, Grove St, Los Angeles',
    },
    {
        date: '2016-05-02',
        name: 'Tom',
        address: 'No. 189, Grove St, Los Angeles',
    },
    {
        date: '2016-05-04',
        name: 'Tom',
        address: 'No. 189, Grove St, Los Angeles',
    },
    {
        date: '2016-05-01',
        name: 'Tom',
        address: 'No. 189, Grove St, Los Angeles',
    },
];

const rules = reactive<FormRules>({
    paymentAmount: [
        { required: true, message: '请输入付款金额', trigger: 'blur' },
        { type: 'number', min: 0, message: '请输入金额并且不能小于0', trigger: 'blur' },

    ],
    payer: [
        { required: true, message: '请输入付款人/单位', trigger: 'blur' },
    ],
    fileUrl: [
        { required: true, message: '请上传凭证', trigger: 'blur' },
    ],
    paymentAccountId: [
        {
            required: true,
            message: '请选择付款账号',
            trigger: ['blur', 'change'],
        },
    ],
    paymentDate: [
        {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change'],
        },
    ],
});


/** 付款信息 */
const monitorCheng = () => {
    const { payer, paymentAmount, paymentDate, paymentAccountId } = ruleForm;

    let paymentAccountName = '';
    if (paymentAccountId) {
        paymentAccountName = props.allPaymentCardList.filter((item: any) => item.id == paymentAccountId)[0].name;
    }

    ruleForm.paymentInfo = `${paymentAccountName} ${paymentAmount ?? paymentAmount + '元'
        } ${paymentDate} ${payer}`;
};

/** 上传效果图 */
const handleDesignSketchSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    dialogVisible.value.close()

    ruleForm.fileUrl = response.data.url
};

const beforedeSignSketchUpload: UploadProps['beforeUpload'] = () => {
    dialogVisible.value = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
};

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {

            const query = {
                businessId: props.initList.id,
                ...ruleForm
            }

            try {
                const { code } = await addAccountsPayableApi(query)
                if (code == 200) {
                    proxy?.$modal.msgSuccess('操作成功');
                    emits('submit', true);

                    handleClose();
                }
            } catch (error) {

            }


        } else {
            console.log('error submit!', fields)
        }
    })
}


const handleClose = () => {
    ruleFormRef.value?.resetFields();
    emits('close');
};

onMounted(() => {
})
</script>

<style lang="scss" scoped>
::v-deep .el-upload-dragger {
    padding: 0px 4px !important;
    height: 100px !important;
    width: 260px;
}

::v-deep .el-divider--horizontal {
    margin: 12px 0;
}
</style>